<template>
      <div class="list" >
        <ul
          v-for="item of letters"
          :key="item"
          :ref="item"
          @click="handleLetterClick"
          @touchstart="handleTouchStart"
          @touchmove="handleTouchMove"
          @touchend="handleTouchEnd"
        >
          <li class="item">{{item}}</li>
        </ul>
      </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  watch: {
    startY () {
      return this.$refs['A'][0].offsetTop
    }
  },
  computed: {
    letters () {
      const letters = []
      for (let i in this.cities) { // for...in 循环获取的第一个参数是key, 区别于for...of
        letters.push(i)
      }
      return letters
    }
  },
  methods: {
    handleLetterClick (e) {
      this.$emit('change', e.target.innerHTML)
    },
    handleTouchStart () {
      // console.log(1)
      this.touchStatus = true
    },
    handleTouchMove (e) {
      // console.log(2)
      if (this.touchStatus) {
        // 1.增加的内容, 节流 与防抖, 网页性能优化=================
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          // 1.获取字母A距离容器顶部的高度 (就是蓝色的下面开始计算)
          // const startY = this.$refs['A'][0].offsetTop
          // 2.获取当前位置与屏幕顶部的位置 - 79(顶部header+search的高度)
          const touchY = e.touches[0].clientY - 79
          // 3.当前位置的offsetTop - A的offsetTop / 20(每个字母的高度),
          //   从而计算出当前字母的位置0 - 21 不是26个字母哦
          const index = Math.floor((touchY - this.startY) / 20)
          // console.log(this.letters[index])
          if (index >= 0 && index < this.letters.length) {
            this.$emit('change', this.letters[index])
          }
        }, 17)
      }
    },
    handleTouchEnd () {
      // console.log(3)
      this.touchStatus = false
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display flex
    flex-flow column nowrap
    justify-content  center
    align-items center
    position absolute
    top 1.58rem
    right 0
    bottom 0
    width .4rem
    .item
      color $bgColor
      font-size .30rem
      line-height .4rem
      touch-action none
      /*无法被动侦听事件preventDefault，是新版本chrome 浏览器报错。*/
</style>
